package com.dawson.pdf;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    Handler updateHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {

            }
            return true;
        }
    });

    private TextView tvTitle, tvC;


    private String title = "";
    private long endTime = 0L;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒", Locale.CHINA);
    PdfDocument document = null;
    int numberOfPages = -1;
    int cPage = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main2);
        tvC = findViewById(R.id.tv_content);


        findViewById(R.id.btn_show).setOnClickListener(v -> {
            // 读取一个PDF文件并构建PDF文档
            if (document == null) {
                try {
                    PdfDocument document = new PdfDocument(new PdfReader("/storage/emulated/0/Documents/2_goodbye.pdf"));
                    numberOfPages = document.getNumberOfPages();
                    cPage = 0;
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, "read pdf failed:" + e.getMessage(), Toast.LENGTH_LONG).show();
                    return;
                }
            }

            String textFromPage = PdfTextExtractor.getTextFromPage(document.getPage(cPage++));
            tvC.setText(textFromPage);

            Toast.makeText(MainActivity.this, "read pdf:" + cPage, Toast.LENGTH_LONG).show();


            updateHandler.sendMessage(updateHandler.obtainMessage(1));

        });

        SharedPreferences sp = getSharedPreferences("dawson_sp", Context.MODE_PRIVATE);


        updateHandler.sendMessage(updateHandler.obtainMessage(1));
    }

}